package com.lighting.smssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.mapper.MetricMapper;
import com.lighting.smssystem.mapper.UserMapper;
import com.lighting.smssystem.model.Metric;
import com.lighting.smssystem.model.User;
import com.lighting.smssystem.model.bo.UserList;
import com.lighting.smssystem.service.IUserService;
import com.lighting.smssystem.utils.SnowflakeIdWorker;
import com.lighting.smssystem.utils.ThreadContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.query;
import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

/**
 * @author leemaster
 * @Title: UserService
 * @Package com.lighting.smssystem.service.impl
 * @Description:
 * @date 2019-06-0123:47
 */
@Service
public class UserService implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MetricMapper metricMapper;


    @Override
    public UserList listUsers(Integer limit, Integer offset) {

        Page<User> page = new Page<>(offset,limit);

        IPage<User> userIPage = userMapper.selectPage(
                page, Wrappers.<User>query().in("user_role",UserRole.VIP,UserRole.COMMON)
        );
        Long total = userIPage.getTotal();
        return new UserList(total, userIPage.getRecords(), (long) offset, (long) limit, (long) Math.ceil((total / limit)));
    }

    @Override
    public UserList listAdmin(Integer limit, Integer offset) {
        Page<User> page = new Page<>(offset,limit);

        IPage<User> userIPage = userMapper.selectPage(
                page, Wrappers.<User>query().eq("user_role",UserRole.ADMIN)
        );
        Long total = userIPage.getTotal();
        return new UserList(total,userIPage.getRecords(), (long) offset, (long) limit, (long) Math.ceil((total / limit)));
    }

    @Override
    public int createAdminUser(User user) {
        user.setUserId(SnowflakeIdWorker.next());
        user.setUserRole(UserRole.ADMIN);

        return userMapper.insert(user);
    }

    @Override
    public int revokeAdmin(Long id) {
        User user = new User();
        user.setUserRole(UserRole.COMMON);
        return userMapper.update(user,Wrappers.<User>update().eq("user_id",id));
    }

    @Override
    public Metric metric(Long userId) {
        QueryWrapper<Metric> condition = new QueryWrapper<>();
        condition.eq("metric_user",userId);
        Metric metric = metricMapper.selectOne(condition);
        if (metric == null) {
            metric = new Metric();
            metric.setMetricUser(userId);
            metric.setMetricId(SnowflakeIdWorker.next());
            metric.setMetricLeft(0);
            metric.setMetricLimit(0);
            metricMapper.insert(metric);
            return metric;
        }
        return metric;
    }

    @Override
    public int updateMetric(Metric metric) {
        return metricMapper.update(metric, Wrappers.<Metric>update().eq("metric_user", metric.getMetricUser()));
    }

    @Override
    public int activationVip(Long userId) {
        User user = userMapper.selectOne((new QueryWrapper<User>()).eq("user_id", userId));
        if (user.getUserRole().equals(UserRole.VIP)) {
            user.setUserRole(UserRole.COMMON);
        } else if (user.getUserRole().equals(UserRole.COMMON)){
            user.setUserRole(UserRole.VIP);
        }
        return userMapper.update(user, Wrappers.<User>update().eq("user_id", userId));
    }

    @Override
    public int createUser(User user) {
        user.setUserId(SnowflakeIdWorker.next());
        user.setUserRole(UserRole.COMMON);
        return userMapper.insert(user);
    }

    @Override
    public boolean verifyPhone(String phone) {
        List<User> userList = userMapper.selectList(Wrappers.<User>query().eq("user_phone", phone));
        if (userList.size() <= 0) {
            return true;
        }
        return false;
    }

    @Override
    public User queryByPhone(String phone) {
        return userMapper.selectOne(Wrappers.<User>query().eq("user_phone", phone));
    }

    @Override
    public User queryById(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.update(user, Wrappers.<User>update().eq("user_id", user.getUserId()));
    }

    @Override
    public int resetUserPwd(Long id) {
        User user = queryById(id);
        user.setUserPassword("moshangwang");
        return updateUser(user);
    }

    @Override
    public int reduceMeric(Long id, int phoneSize) {
        Metric metric = metric(id);
        if (metric.getMetricLimit() - phoneSize < 0) {
            return -2;
        }
        // 如果用量为空 不允许发送短信
        if (metric.getMetricLeft() - phoneSize < 0) {
            return -1;
        }
        metric.setMetricLeft(metric.getMetricLeft() - phoneSize);
        return updateMetric(metric);
    }
}
